package com.apexedu.portal.controller;

import com.apexedu.biz.Const;
import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.jdbc.DataSourceEntity;
import com.apexedu.framework.jdbc.DataSourceManager;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.identity.IdConstants;
import com.apexedu.identity.action.IdLoginAction;
import com.apexedu.identity.entity.TSysUser;
import com.apexedu.portal.constant.ActionConstant;
import com.apexedu.portal.entity.TDb;
import com.apexedu.portal.entity.TLbxx;
import com.apexedu.portal.entity.TLbxxSz;
import com.apexedu.portal.entity.TLbxxSzMx;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.portal.util.LittleTimer;
import com.apexedu.sys.entity.ApplicationEnum;
import com.apexedu.sys.util.BusinessLogUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.json.JsonUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * 列表信息配置 包括流程管理 代办信息 通知公告等
 * Created by ly on 2014/8/8.
 */
@Controller
public class LbxxController extends BaseController {

	@Resource
	private BaseDao baseDao;

	/**
	 * 初始界面
	 *
	 * @return 初始界面
	 */
	@RequestMapping(value = ActionConstant.Lbxx.RequestMapping_init, method = RequestMethod.GET)
	public String init() {
		debug("<<{}>> init start", this.getClass().getSimpleName());
		LittleTimer timer = new LittleTimer();
		try {
			return ActionConstant.Lbxx.Forward_init;
		} catch (Exception e) {
			error("<<{}>> init error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> init end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 树结构
	 *
	 * @return 初始界面
	 */
	@RequestMapping(value = ActionConstant.Lbxx.RequestMapping_tree, method = RequestMethod.GET)
	public String tree(HttpServletRequest request, ModelMap map) {
		debug("<<{}>> tree start", this.getClass().getSimpleName());
		LittleTimer timer = new LittleTimer();
		try {
			//树结构类型 checkbox/radio/正常 默认为正常
			String chkStyle = request.getParameter("chkStyle");
			map.put("chkStyle", chkStyle);

			//是否流程待办组件,流程待办组件只显示待办
			String workflow = request.getParameter("workflow");
			map.put("workflow", workflow);

			return ActionConstant.Lbxx.Forward_tree;
		} catch (Exception e) {
			error("<<{}>> tree error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> tree end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 获取信息列表集合
	 *
	 * @param request --
	 * @return 信息列表集合
	 */
	@RequestMapping(value = ActionConstant.Lbxx.RequestMapping_getListXx, method = RequestMethod.GET)
	@ResponseBody
	public String getListXx(HttpServletRequest request) {
		debug("<<{}>> getListXx start", this.getClass().getSimpleName());
		LittleTimer timer = new LittleTimer();
		try {
			List<TLbxx> list = DBUtil.queryAllBeanList("select * from T_Lbxx where 1=1 order by orderno", TLbxx.class);
			String jsonStr = JsonUtil.getJSONString(list);
			debug("<<{}>> getListXx : jsonstr : {}", this.getClass().getSimpleName(), jsonStr);
			return jsonStr;
		} catch (Exception e) {
			error("<<{}>> getListXx error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> getListXx end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 维护列表信息界面
	 *
	 * @param request --
	 * @param map --
	 * @return 列表信息界面
	 */
	@RequestMapping(value = ActionConstant.Lbxx.RequestMapping_edit, method = RequestMethod.GET)
	public String edit(HttpServletRequest request, ModelMap map) {
		debug("<<{}>> edit start", this.getClass().getSimpleName());
		LittleTimer timer = new LittleTimer();
		try {
			String wid = request.getParameter("wid");
			TLbxx lbxx;
			if (StringUtil.isNotBlank(wid)) {
				debug("<<{}>> edit : wid : {}", this.getClass().getSimpleName(), wid);
				lbxx = DBUtil.queryBean("select * from t_lbxx where wid = ?", TLbxx.class, wid);
				if (StringUtil.isNotBlank(lbxx.getUpid()) && !"0".equals(lbxx.getUpid())) {
					lbxx.setUpname((String) DBUtil.queryFieldValue("select name from t_lbxx where wid=?", lbxx.getUpid()));
				}
			} else {
				String upid = request.getParameter("upid");
				lbxx = new TLbxx();
				lbxx.setWid(upid.substring(0, 1) + SeqFactory.getNewSequenceAlone());
				lbxx.setLx(upid.substring(0, 1));
				lbxx.setUpid(upid);
				lbxx.setUpname((String) DBUtil.queryFieldValue("select name from t_lbxx where wid=?", upid));
			}
			map.put("lbxx", lbxx);

			//数据源列表
			List<ApplicationEnum> listCode = DBUtil.queryAllBeanList("select a.code as id,a.name as caption,a.* from t_db a" + " where a.state='1' order by a.wid ", ApplicationEnum.class);
			map.put("listCode", listCode);
			return ActionConstant.Lbxx.Forward_edit;
		} catch (Exception e) {
			e.printStackTrace();
			error("<<{}>> edit error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> edit end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 保存列表信息
	 *
	 * @param lbxx 列表信息
	 * @param map --
	 * @return 列表信息维护界面
	 */
	@RequestMapping(value = ActionConstant.Lbxx.RequestMapping_edit, method = RequestMethod.POST)
	public String save(TLbxx lbxx, ModelMap map, HttpServletRequest request) {
		debug("<<{}>> save start", this.getClass().getSimpleName());
		LittleTimer timer = new LittleTimer();
		TSysUser tSysUser = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);

		try {
			//sql url moreurl反转义
			lbxx.setSql(StringUtil.unescapeHtml(lbxx.getSql()));
			lbxx.setUrl(StringUtil.unescapeHtml(lbxx.getUrl()));
			lbxx.setMoreurl(StringUtil.unescapeHtml(lbxx.getMoreurl()));
			if (StringUtil.isNotBlank(lbxx.getWid()) && baseDao.count(" from TLbxx where wid = ?", lbxx.getWid()) > 0) {
				baseDao.updateNotNull(lbxx);
				BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX, Const.LOG_ACTION_UPDATE, IdLoginAction.getIpAddr(request));
			} else {
				baseDao.save(lbxx);
				BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX, Const.LOG_ACTION_SAVE, IdLoginAction.getIpAddr(request));
			}
			List<TLbxx> list = new ArrayList<TLbxx>();
			if (lbxx.getUpid().length() == 1 && !"0".equals(lbxx.getUpid())) {
				if ("1".equals(lbxx.getLx())) {//流程待办
					list = new DBMUtil(lbxx.getDb()).queryAllBeanList("select wf_name as des,wf_describe as name from OS_WORKFLOWDEFS", TLbxx.class);
				} else if ("2".equals(lbxx.getLx())) {//通知公告
					list = new DBMUtil(lbxx.getDb()).queryAllBeanList("SELECT id as des,classname as name," + "'/nj6.1.2-portlet/html/tzgg/detail.jsp' as url,'/nj6.1.2-portlet/html/tzgg/list.jsp?type='||id as moreurl" + "  from  lbNewsClass",
							TLbxx.class);
				}
				if (!list.isEmpty()) {
					DBUtil.executeSQL("delete from t_lbxx where upid = ?", lbxx.getWid());
					BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX, Const.LOG_ACTION_DEL, IdLoginAction.getIpAddr(request));
					for (TLbxx lb : list) {
						lb.setWid(lbxx.getWid() + lb.getDes());
						lb.setUpid(lbxx.getWid());
						lb.setLx(lbxx.getLx());
						lb.setDb(lbxx.getDb());
						lb.setState("1");
					}
					baseDao.saveAll(list);
				}
			}

			debug("<<?>> save , lbxx : {}", this.getClass().getName(), lbxx.toString());
			map.put("save", true);
			lbxx.setUpname((String) DBUtil.queryFieldValue("select name from t_lbxx where wid=?", lbxx.getUpid()));
			map.put("lbxx", lbxx);

			//数据源列表
			//            List<ApplicationEnum> listCode = DBUtil.queryAllBeanList("select zdbm as id,zdmc as caption from t_sys_code a" +
			//                    " where zdlb='sjy' order by zdpx ", ApplicationEnum.class);
			List<ApplicationEnum> listCode = DBUtil.queryAllBeanList("select a.code as id,a.name as caption,a.* from t_db a" + " where a.state='1' order by a.wid ", ApplicationEnum.class);
			map.put("listCode", listCode);
			return ActionConstant.Lbxx.Forward_edit;
		} catch (Exception e) {
			e.printStackTrace();
			error("<<{}>> save error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> save end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 删除列表信息
	 *
	 * @param id 列表信息wid
	 */
	@RequestMapping(value = ActionConstant.Lbxx.RequestMapping_delete, method = RequestMethod.POST)
	@ResponseBody
	public void delete(@PathVariable(ActionConstant.Variable_Id) String id, HttpServletRequest request) {
		debug("<<{}>> delete start , id : {}", this.getClass().getSimpleName());
		TSysUser tSysUser = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		LittleTimer timer = new LittleTimer();
		try {
			DBUtil.executeSQL("delete from t_lbxx where wid = ?", id);
			BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX, Const.LOG_ACTION_DEL, IdLoginAction.getIpAddr(request));
			DBUtil.executeSQL("delete from t_lbxx_sz_mx where lbxxid = ?", id);
			BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX_SZ_MX, Const.LOG_ACTION_DEL, IdLoginAction.getIpAddr(request));
		} catch (Exception e) {
			e.printStackTrace();
			error("<<{}>> delete error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> delete end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 保存列表设置信息
	 */
	@RequestMapping(value = ActionConstant.Lbxx.RequestMapping_saveLbxxSz, method = RequestMethod.POST)
	@ResponseBody
	public void saveLbxxSz(HttpServletRequest request) {
		debug("<<{}>> saveLbxxSz start", this.getClass().getSimpleName());
		TSysUser tSysUser = (TSysUser) request.getSession().getAttribute(IdConstants.SESSION_USER);
		LittleTimer timer = new LittleTimer();
		try {
			TLbxxSz sz = (TLbxxSz) JsonUtil.getDTO(request.getParameter("sz"), TLbxxSz.class);
			for (int i = 0; i < sz.getMxList().size(); i++) {
				sz.getMxList().set(i, (TLbxxSzMx) JsonUtil.getDTO(JsonUtil.getJSONString(sz.getMxList().get(i)), TLbxxSzMx.class));
			}
			if (StringUtil.isNotBlank(sz.getWid())) {//修改
				baseDao.updateNotNull(sz);
				BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX_SZ, Const.LOG_ACTION_UPDATE, IdLoginAction.getIpAddr(request));
				baseDao.executeHql("delete from TLbxxSzMx where szid = ?", sz.getWid());
				BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX_SZ_MX, Const.LOG_ACTION_DEL, IdLoginAction.getIpAddr(request));
			} else {
				sz.setWid(SeqFactory.getNewSequenceAlone());
				baseDao.save(sz);
				BusinessLogUtil.log(tSysUser.getUserloginid(), Const.CZDX_T_LBXX_SZ, Const.LOG_ACTION_SAVE, IdLoginAction.getIpAddr(request));
			}
			for (TLbxxSzMx mx : sz.getMxList()) {
				mx.setWid(SeqFactory.getNewSequenceAlone());
				mx.setSzid(sz.getWid());
			}
			baseDao.saveAll(sz.getMxList());
		} catch (Exception e) {
			error("<<{}>> saveLbxxSz error : {}", this.getClass().getSimpleName(), e);
			throw new RuntimeException(e);
		} finally {
			debug("<<{}>> saveLbxxSz end : {}", this.getClass().getSimpleName(), timer.end());
		}
	}

	/**
	 * 根据数据库编码获取数据库操作模板
	 *
	 * @param dbcode 数据库编码
	 * @return
	 */
	private JdbcTemplate getDateSource(String dbcode) {
		try {
			DataSource ds = DataSourceManager.getDataSource(dbcode);
			return new JdbcTemplate(ds);
		} catch (Exception e) {
			TDb db = DBUtil.queryBean("select * from t_db where code = ?", TDb.class, dbcode);
			if (db == null) {
				throw new RuntimeException("该数据源未配置：" + dbcode);
			}
			DataSourceEntity entity = new DataSourceEntity();
			entity.setDataSourceName(db.getCode());
			entity.setDriver(db.getDriver());
			entity.setUrl(db.getUrl());
			entity.setUsername(db.getUsername());
			entity.setPassword(db.getPwd());
			entity.setMinPoolSize(3);
			DataSourceManager.putNewDataSource(entity);
			DataSource ds = DataSourceManager.getDataSource(dbcode);
			return new JdbcTemplate(ds);
		}
	}
}
